<template>
  <div>
    <div style="display: flex;justify-content: space-between; width: 100%">
      <el-form
        :model="formData"
        label-position="left"
        label-width="100px"
        :rules="ruleForm"
        ref="ruleForm"

      >
        <el-form-item label="商户选择" prop="shop_id">
          <el-select v-model="formData.shop_id" clearable placeholder="请选择商户">
            <el-option
              v-for="item of merchantList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品类型" prop="type">
          <el-select v-model="formData.type" clearable placeholder="请选择商品类型">
            <el-option
              v-for="(item, type) of COMMODITY_TYPE"
              :key="type"
              :label="item"
              :value="Number(type)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="formData.name" style="width: 200px" type="text" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品规格" class="is-required" prop="sku">
          <div v-for="(item,index) in priceList" :key="index"
               style="margin-bottom: 6px;">
            <el-input v-model="item.name" type="text" style="width: 200px" placeholder="请输入规格" />
            <el-input v-model="item.price" type="number"
                      oninput="value=value.replace(/[^\d^\.]+/g,'')"
                      style="width: 200px;margin: 0 12px" placeholder="请输入价格" />
            <el-input v-model="item.stock" type="number"
                      oninput="value=value.replace(/^(0+)|[^\d]+/g,'')"
                      style="width: 200px;margin: 0 12px" placeholder="请输入库存" />
            <i class="el-icon-circle-plus-outline"
               style="font-size: 24px;cursor: pointer;"
               @click="handleAddOrDetele(index,'add')"></i>
            <i class="el-icon-remove-outline"
               style="font-size: 24px;cursor: pointer;"
               @click="handleAddOrDetele(index,'dir')"></i>
            <el-upload
              class="up-load"
              :class="item.img && item.img.length > 0 ? 'hidden':''"
              action="https://up.qiniup.com"
              :limit="1"
              :data="uploadData"
              accept="image/*"
              :file-list="item.img"
              list-type="picture-card"
              :before-upload="beforeAvatarUpload"
              :on-success="(response,file,fileList) => {upSuccess(response,file,fileList,'sku',index)}"
              :on-exceed="()=>{$message.warning({ message: '上传图片最大为1张' })}"
              :on-remove="(file,fileList) => {handleRemove(file,fileList,'sku',index)}"
            >
              <i slot="default" class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="商品轮播" prop="imgs_json">
          <el-upload
            class="up-load"
            :class="formData.imgs_json && formData.imgs_json.length > 9 ? 'hidden':''"
            multiple
            action="https://up.qiniup.com"
            :limit="10"
            :data="uploadData"
            accept="image/*"
            :file-list="formData.imgs_json"
            list-type="picture-card"
            :before-upload="beforeAvatarUpload"
            :on-success="upSuccess"
            :on-exceed="overMax"
            :on-remove="handleRemove"
          >
            <i slot="default" class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情内容" prop="content_html">
          <Tinymce v-model="formData.content_html"  :height="300"/>
        </el-form-item>
      </el-form>
    </div>
    <div style="margin: 5% 0 0 5%;">
      <el-button plain style="margin-right: 3%;" @click="$emit('close')">取消</el-button>
      <el-button type="primary" @click="handleChangeStudentInfo">保存</el-button>
    </div>
  </div>
</template>

<script>
import TableMixins from '@/components/WxTables/mixins'
import Tinymce from '@/components/Tinymce/Tinymce'
import {COMMODITY_TYPE} from '@/views/constants'
import { tourShopGetListByCon } from '@/api/merchant'
export default {
  name: 'CommodityInfo',
  components: {
    Tinymce
  },
  mixins: [TableMixins],
  props: {
    formData: {
      type: Object
    }
  },
  data() {
    return {
      tags: [],
      inputVisible: false,
      inputValue: '',
      qiNiuToken: '',
      COMMODITY_TYPE,
      ruleForm: {
        shop_id: [
          { required: true, message: '请选择商户', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择商户类型', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请填写商品名称', trigger: 'blur' }
        ],
        imgs_json: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ],
        content_html: [
          { required: true, message: '请填写详情内容', trigger: 'blur' }
        ],
      },
      merchantList: [],
      parentIndex: 0,
      editIsAdd: '',
      isType: '',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      addParentsList: {
        relationship: '',
        name: '',
        tel_num: '',
        img: ''
      },
      imageUrl: '',
      parentsIndex: 0,
      editJanitor: false,
      select_dept: [],
      priceList: [
        {name:'',price:NaN,stock:NaN}
      ]
    }
  },
  created(){
    this.firstLoad = false
    this.tags = this.formData.label_arr
    this.getMerchantList()
    if(this.formData.sku) {
      this.priceList = this.formData.sku.map(res=> {
        const { id, name, price, img, stock } = res
        const img_List = [{url:res.img[0],uid: res.img[0].substring(29)}]
        return {id,name,price,img:img_List,stock}
      })
    }
  },
  methods: {
    /**
     * 获取商户列表
     */
    getMerchantList() {
      tourShopGetListByCon({town_id:this.town_id,level:'label',is_paginate:0}).then(res => {
        this.merchantList = res.data
      })
    },
    /**
     * 监控上传数量
     */
    overMax() {
      this.$message.warning({ message: '上传图片最大为10张' })
    },
    /**
     * 得到上传成功的文件
     * @param fileList
     * @param type
     */
    getFile(fileList,type,index) {
      if(type === 'sku' ) {
        this.$set(this.priceList[index],'img',fileList)
      }else{
        this.$set(this.formData,'imgs_json',fileList)
      }
    },
    /**
     * 删除图片
     * @param fileList
     */
    deleteFile(fileList,type,index) {
      if(type === 'sku' ) {
        this.$set(this.priceList[index],'img',fileList)
      }else{
        this.$set(this.formData,'imgs_json',fileList)
      }
    },
    handleAddOrDetele(index,type) {
      if(type === 'add') {
        this.priceList.push({name:'',price:NaN,stock:NaN})
      }else{
        this.priceList.splice(index,1)
      }
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleIsAdd(type, index) {
      this.editIsAdd = type
      this.parentIndex = index
      if (type === 'create') {
        this.isType = '添加'
        this.addParentsList = {}
      }
      if (type === 'edit') {
        this.isType = '编辑'
        this.addParentsList = JSON.parse(JSON.stringify(this.formData.parents[index]))
      }
      this.editJanitor = true
    },
    beforeAddAvatarUpload(file) {
      uploadNormalFile(file, (res) => {
        this.$set(this.addParentsList, 'img', res)
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    /**
     * 保存
     */
    handleChangeStudentInfo() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if(this.priceList.filter(res=> !res.name || !res.price || !res.stock || !res.img || !res.img.length ).length) return this.$message.warning('请确认商品规格完整')

          let price_list = JSON.parse(JSON.stringify(this.priceList))
          let list = JSON.parse(JSON.stringify(this.formData));
          price_list.forEach(res=> {
            if(res.img) {
              res.img = [res.img[0].name ? this.img_url + res.img[0].response.key : this.img_url + res.img[0].uid]
            }
          })
          if(this.formData.imgs_json && this.formData.imgs_json.length){
            list.imgs_json = this.formData.imgs_json.map(item => {
              return item.name ? this.img_url + item.response.key : this.img_url + item.uid
            })
          }
          for (let i in list){
            if(['start_time'].includes(i)){
              list.work_day_start = this.$dayjs(list[i][0]).format('HH:mm')
              list.work_day_end = this.$dayjs(list[i][1]).format('HH:mm')
            }
            if(['end_time'].includes(i)){
              list.rest_day_start = this.$dayjs(list[i][0]).format('HH:mm')
              list.rest_day_end = this.$dayjs(list[i][1]).format('HH:mm')
            }
          }
          for (let i in list){
            if(['start_time','end_time'].includes(i)){
              delete list[i]
            }
          }
          list.sku = price_list
          this.$emit('saveFrom',list)
        } else {
          return false;
        }
      });
    },
  }
}
</script>
<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.time_title{
  font-size: 14px;
  color: #606266;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.up-load {
  margin-top: 6px;
}
.hidden >>> .el-upload--picture-card {
  display: none;
}
</style>
<style lang="scss" src="./style/Form.scss" scoped>

</style>
